package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.AccraditationRecordConstant;
import com.zzyl.dto.BedDto;
import com.zzyl.dto.CheckInConfigDto;
import com.zzyl.entity.CheckIn;
import com.zzyl.entity.CheckInConfig;
import com.zzyl.entity.Elder;
import com.zzyl.entity.User;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.CheckInConfigMapper;
import com.zzyl.mapper.CheckInMapper;
import com.zzyl.mapper.ElderMapper;
import com.zzyl.service.*;
import com.zzyl.utils.CodeUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.BedVo;
import com.zzyl.vo.RecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class CheckInConfigServiceImpl implements CheckInConfigService {

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedService bedService;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ActFlowCommService actFlowCommService;

    @Autowired
    private AccraditationRecordService accraditationRecordService;

    /**
     * 养老顾问-入住选配
     * @param dto
     * @return
     */
    @Override
    public ResponseResult checkIn(CheckInConfigDto dto) {
        //1,判断费用期限是否在入住期限之内,如果不是则直接抛出异常
        if(dto.getCheckInStartTime().isAfter(dto.getCostStartTime()) || dto.getCheckInEndTime().isBefore(dto.getCostEndTime())){
            throw new BaseException("费用期限必须在入住期限之内!");
        }
        //2,新增入住配置信息
        CheckInConfig checkInConfig = BeanUtil.toBean(dto, CheckInConfig.class);

        //3,根据床位id查询床位编号
        BedVo bedVo = bedService.getBedById(dto.getBedId());
        checkInConfig.setBedNo(bedVo.getBedNumber());

        //备注信息  楼层id:房间id:床位id:楼层名称:房间编号
        checkInConfig.setRemark(dto.getFloorId()+":"+dto.getRoomId()+":"+dto.getBedId()+":"+dto.getFloorName()+":"+dto.getCode());
        checkInConfigMapper.insert(checkInConfig);

        //4,更新床位状态信息
        BedDto bedDto = BeanUtil.toBean(bedVo, BedDto.class);
        bedDto.setBedStatus(2);
        bedService.updateBed(bedDto);

        //5,保存床位与老人关系
        Elder elder = elderMapper.selectByPrimaryKey(checkInConfig.getElderId());
        elder.setBedId(dto.getBedId());
        elder.setBedNumber(bedVo.getBedNumber());
        elderMapper.updateByPrimaryKeySelective(elder);

        //6,更新入住状态信息
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(dto.getCheckInId());
        checkIn.setFlowStatus(CheckIn.FlowStatus.SIGN.getCode());
        checkIn.setCheckInTime(dto.getCheckInStartTime());
        //合同编号
        String htCode = CodeUtil.generateCode("HT", redisTemplate, 5);
        checkIn.setRemark(htCode);
        checkInMapper.updateByPrimaryKeySelective(checkIn);
        //7,完成任务
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        actFlowCommService.completeProcess(
                null,
                dto.getTaskId(),
                user.getId().toString(),
                1,
                null
        );

        //8,保存操作记录
        Long nextAssignee = actFlowCommService.getNextAssignee("checkIn","checkIn:" + checkIn.getId());
        RecordVo recordVo = getRecordVo(
                checkIn,
                user,
                AccraditationRecordConstant.AUDIT_STATUS_PASS,
                "同意",
                "养老顾问处理-入住配置",
                "法务处理-签约办理",
                nextAssignee,
                AccraditationRecordConstant.RECORD_HANDLE_TYPE_PROCESSED
        );
        accraditationRecordService.insert(recordVo);
        return ResponseResult.success();
    }

    @Override
    public CheckInConfig findCurrentConfigByElderId(Long elderId) {
        CheckInConfig checkInConfig = checkInConfigMapper.findCurrentConfigByElderId(elderId);
        return checkInConfig;
    }


    /**
     * 获取操作记录RecordVo
     *
     * @param checkIn        入住对象
     * @param user           当前用户
     * @param status         审批状态 1:通过 2:拒绝 3:驳回  4:撤回  5:撤销
     * @param option         意见
     * @param step           当前步骤
     * @param nextStep       下一个操作步骤
     * @param nextAssigneeId 下一个审核人id
     * @param handleType     处理类型 0:已审批 1：已处理
     * @return
     */
    private RecordVo getRecordVo(CheckIn checkIn, User user, Integer status, String option, String step, String nextStep, Long nextAssigneeId, Integer handleType) {
        RecordVo recordVo = new RecordVo();
        recordVo.setId(checkIn.getId());
        recordVo.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
        recordVo.setFlowStatus(checkIn.getFlowStatus());
        recordVo.setHandleType(handleType);
        recordVo.setStatus(status);
        recordVo.setOption(option);
        recordVo.setStep(step);
        recordVo.setNextStep(nextStep);
        recordVo.setRealName(user.getRealName());
        recordVo.setUserId(user.getId());
        recordVo.setNextAssignee(nextAssigneeId);
        return recordVo;
    }
}
